package com.lihua.newideas.controller;

import cn.hutool.core.date.DateUtil;
import com.lihua.newideas.pojo.JsonResult;
import com.lihua.newideas.pojo.UploadSystem;
import com.lihua.newideas.pojo.UserManuscript;
import com.lihua.newideas.pojo.UserManuscript;
import com.lihua.newideas.service.UserManuscriptService;
import com.lihua.newideas.uploadUtil.UploadUtil;
import jdk.nashorn.internal.runtime.Context;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Controller
public class UserManuscriptController {
    
    @Autowired
    UserManuscriptService userManuscriptService;

    /*
     * 投稿视图
     * */
    @RequestMapping("/contribution/{userName}")
    public String contribution(@PathVariable("userName") String userName , Model model){
        List<UserManuscript> userManuscripts = userManuscriptService.queryUserManuscriptByUserName(userName);
        model.addAttribute("userManuscripts",userManuscripts);
        return "file_upload";
    }
    
    /*
    * 上传稿件
    * */
    @RequestMapping("/uploadManuscript/{userName}")
    @ResponseBody
    public JsonResult uploadFile(@PathVariable("userName") String userName ,@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) {
        /*
         * upload 封装的函数
         * */
        JsonResult newIdeasFile = upload(userName,file, request, "manuscript");
        return newIdeasFile;
    }
    /*
    * 根据稿件状态查询
    * */
    @RequestMapping("/admin/getManuscript/{manuscriptStatus}")
    public String getManuscript(@PathVariable("manuscriptStatus") String manuscriptStatus , Model model){
        List<UserManuscript> userManuscripts = userManuscriptService.queryUserManuscriptByStatus(Long.valueOf(manuscriptStatus));
        model.addAttribute("userManuscripts",userManuscripts);
        return "admin/user_manuscript";
    }

    /*
    * 根据id修改稿件状态
    * */
    @RequestMapping("/admin/updateManuscriptStatus")
    @ResponseBody
    public String updateManuscriptStatus(String id ,String status){
//        System.out.println("id:"+id+status);
        userManuscriptService.updateManuscriptStatusById(Long.valueOf(id),Long.valueOf(status));
        return "成功";
    }

    /*
    * 下载稿件
    * */
    @RequestMapping("/manuscript/download/{id}/{fileName}")
    @ResponseBody
    public void download(
            @PathVariable("fileName") String filename,@PathVariable("id") String id
    ) throws IOException {

        UserManuscript userManuscript = userManuscriptService.queryManuscriptById(Long.valueOf(id));

        String fileName =filename+userManuscript.getManuscriptSuffix();  //获取文件名和扩展名

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        // 设置信息给客户端不解析
        String type = new MimetypesFileTypeMap().getContentType(fileName); //获取文件名和扩展名
        // 设置contenttype，即告诉客户端所发送的数据属于什么类型
        response.setHeader("Content-type",type);
        // 设置编码
        String hehe = new String(fileName.getBytes("utf-8"), "iso-8859-1");
        // 设置扩展头，当Content-Type 的类型为要下载的类型时 , 这个信息头会告诉浏览器这个文件的名字和类型。
        response.setHeader("Content-Disposition", "attachment;filename=" + hehe);

        download(userManuscript.getManuscriptPath(), response);
    }

    public JsonResult upload(String userName, MultipartFile file, HttpServletRequest request, String filePath){
        if(!file.isEmpty()){
            try {
                // 获取用户目录
                String userPath = System.getProperties().getProperty("user.home") +"/newIdeasFile/";
                // 保存目录
                StringBuffer hold = new StringBuffer("upload/"+filePath+"/");
                // 获取时间，以年月创建目录
                Date date = DateUtil.date();
                hold.append(DateUtil.thisYear()).append("/").append(DateUtil.thisMonth() + 1).append("/");
                File mediaPath = new File(userPath, hold.toString());
                // 如果没有该目录则创建
                if (!mediaPath.exists()) {
                    mediaPath.mkdirs();
                }
                
                SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); //创建时间格式

                System.out.println("文件名："+file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."))
                        .replaceAll(" ", "_").replaceAll(",", "") );
                String fileNameNoFileSuffix = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."))
                        .replaceAll(" ", "_").replaceAll(",", "");
                // 生成文件名称
                String nameSuffix = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."))
                        .replaceAll(" ", "_").replaceAll(",", "") + format.format(DateUtil.date())
                        + new Random().nextInt(1000);
                // 文件后缀
                String fileSuffix = file.getOriginalFilename()
                        .substring(file.getOriginalFilename().lastIndexOf(".") + 1);
                // 上传文件名加后缀
                String fileName = nameSuffix + "." + fileSuffix;
                // 转存文件
                file.transferTo(new File(mediaPath.toString(), fileName));

                // 稿件路径
                StringBuffer originalPath = new StringBuffer();
                originalPath.append(mediaPath.getAbsolutePath()).append("/").append(fileName);
                System.out.println("稿件路径++++++" + originalPath);
                // 稿件数据库路径
                StringBuffer originalDataPath = new StringBuffer();
                originalDataPath.append("/").append(hold).append(fileName);
                System.out.println("稿件数据库路径++++++" + originalDataPath);

                UserManuscript UserManuscript = new UserManuscript();

                UserManuscript.setUserName(userName);
                UserManuscript.setManuscriptName(fileNameNoFileSuffix);
                UserManuscript.setManuscriptPath(originalDataPath.toString());
                UserManuscript.setManuscriptType(file.getContentType());
                UserManuscript.setManuscriptCreateDate(date);
                UserManuscript.setManuscriptSuffix(new StringBuffer().append(".").append(fileSuffix).toString());

                UserManuscript.setManuscriptSize(UploadUtil.parseSize(new File(mediaPath.toString() + "/" + fileName).length()));
                UserManuscript.setManuscriptStatus(0);
                userManuscriptService.insertUserManuscript(UserManuscript);
                return new JsonResult(true,originalDataPath.toString());   //上传后必须以这种方式返回文件路径，否则即使上传成功，前台也会显示失败
            }catch (Exception e){
                System.out.println("上传附件错误" + e.getMessage());
                return new JsonResult(false,"失败");
            }

        }else {
            //       加载上传页面
            return new JsonResult(false,"没有选择文件");
        }
    }



    /*
    * 下载工具包
    * */
    public static void download(String filePath, HttpServletResponse res) throws IOException {
        // 获取用户目录
        String userPath = System.getProperties().getProperty("user.home") +"/newIdeasFile/";
        // 发送给客户端的数据
        OutputStream outputStream = null;
        try {

            outputStream = res.getOutputStream();
            byte[] buff = new byte[1024];
            BufferedInputStream bis = null;
            // 读取filename
            bis = new BufferedInputStream(new FileInputStream(new File(userPath+filePath)));
            int i = bis.read(buff);
            while (i != -1) {
                outputStream.write(buff, 0, buff.length);
                outputStream.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            outputStream.close();
        }


    }
}
